package com.hzjh.base.ext.widget.textview

import android.content.Context
import android.graphics.Paint
import android.graphics.Typeface
import android.util.AttributeSet
import android.util.TypedValue
import android.view.LayoutInflater
import android.widget.FrameLayout
import com.hzjh.base.ext.R
import com.hzjh.base.ext.databinding.ViewPriceBinding
import com.hzjh.base.utils.function.color
import com.hzjh.base.utils.function.visibleOrGone
import com.hzjh.base.utils.other.CommUtils

class PriceView @JvmOverloads constructor(
    context: Context,
    attrSet: AttributeSet?,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrSet, defStyleAttr) {

    lateinit var price: Any
    var currency: String? = null
    var showDiscount: Boolean = false//展示划线价格

    private val binding: ViewPriceBinding

    init {
        binding = ViewPriceBinding.inflate(LayoutInflater.from(context), this, true)
        val typedArray = context.obtainStyledAttributes(
            attrSet,
            R.styleable.PriceView
        )

        // 文字大小设置
        binding.tvPrice.setTextSize(
            TypedValue.COMPLEX_UNIT_PX,
            typedArray.getDimensionPixelSize(R.styleable.PriceView_priceTextSize, 20).toFloat()
        )
        binding.tvDecimal.setTextSize(
            TypedValue.COMPLEX_UNIT_PX,
            typedArray.getDimensionPixelSize(R.styleable.PriceView_decimalTextSize, 14).toFloat()
        )
        val symbolSize = typedArray.getDimensionPixelSize(R.styleable.PriceView_symbolTextSize, 12)
        binding.tvPriceSymbol2.setTextSize(TypedValue.COMPLEX_UNIT_PX, symbolSize.toFloat())
        binding.tvPriceSymbol1.setTextSize(TypedValue.COMPLEX_UNIT_PX, symbolSize.toFloat())

        //文字颜色设置
        binding.tvPrice.setTextColor(
            typedArray.getColor(
                R.styleable.PriceView_priceTextColor,
                CommUtils.getColor(com.hzjh.base.style.R.color.coreBlack2)
            )
        )
        val color = typedArray.getColor(
            R.styleable.PriceView_symbolTextColor,
            CommUtils.getColor(com.hzjh.base.style.R.color.coreBlack2)
        )

        binding.tvPriceSymbol1.setTextColor(color)
        binding.tvPriceSymbol2.setTextColor(color)

        binding.tvDecimal.setTextColor(
            typedArray.getColor(
                R.styleable.PriceView_decimalTextColor,
                CommUtils.getColor(com.hzjh.base.style.R.color.coreBlack2)
            )
        )

        //文字粗细设置
        if (typedArray.getBoolean(
                R.styleable.PriceView_priceTextIsBold, true
            )
        ) {
            binding.tvPrice.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD)
        } else {
            binding.tvPrice.setTypeface(Typeface.SANS_SERIF, Typeface.NORMAL)
        }
        if (typedArray.getBoolean(
                R.styleable.PriceView_decimalTextIsBold, false
            )
        ) {
            binding.tvDecimal.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD)
        } else {
            binding.tvDecimal.setTypeface(Typeface.SANS_SERIF, Typeface.NORMAL)
        }
        if (typedArray.getBoolean(
                R.styleable.PriceView_symbolTextIsBold, false
            )
        ) {
            binding.tvPriceSymbol1.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD)
            binding.tvPriceSymbol2.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD)
        }else{
            binding.tvPriceSymbol1.setTypeface(Typeface.SANS_SERIF, Typeface.NORMAL)
            binding.tvPriceSymbol2.setTypeface(Typeface.SANS_SERIF, Typeface.NORMAL)
        }

        showDiscount = typedArray.getBoolean(
            R.styleable.PriceView_isDiscount, false
        )
        typedArray.recycle()
    }


    fun show(price: Any, currency: String?=null, currencySymbol: String?=null) {
        this.price = price
        this.currency = currency

        val currencySymbol: String = if (currencySymbol?.isNotEmpty() == true)
            currencySymbol
        else getCurrencySymbol(currency)
        /// 瑞典	SE	瑞典克朗	SEK	kr
        /// 丹麦	DK	丹麦克朗	DKK	kr.
        /// 都要后置显示
        val isKrSymbol: Boolean = currency == "SEK" || currency == "DKK"

        val priceStrList = getPriceStrList(isKrSymbol)

        if (!showDiscount) {
            if (isKrSymbol) {
                binding.tvPriceSymbol2.visibleOrGone(true) {}
                binding.tvPriceSymbol1.visibleOrGone(false) {}
                binding.tvPriceSymbol2.text = currencySymbol
            } else {
                binding.tvPriceSymbol1.visibleOrGone(true) {}
                binding.tvPriceSymbol2.visibleOrGone(false) {}
                binding.tvPriceSymbol1.text = currencySymbol
            }

            if (priceStrList.isNotEmpty()) {
                binding.tvPrice.text = priceStrList.first()

                if (priceStrList.size > 1) {
                    binding.tvDecimal.visibleOrGone(true) {}
                    binding.tvDecimal.text = priceStrList.last()
                }
            }
        } else {
            var price = ""
            binding.tvPriceSymbol2.visibleOrGone(false) {}
            binding.tvPriceSymbol1.visibleOrGone(false) {}
            binding.tvDecimal.visibleOrGone(false) {}
            if (!isKrSymbol) {
                price = price.plus(currencySymbol)
            }

            if (priceStrList.isNotEmpty()) {
                price = price.plus(priceStrList.first())

                if (priceStrList.size > 1) {
                    price = price.plus(priceStrList.last())
                }
            }
            if (isKrSymbol) {
                price = price.plus(currencySymbol)
            }
            binding.tvPrice.text = price
            binding.tvPrice.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG //中划线
            binding.tvPrice.paint.isAntiAlias = true;//抗锯齿

//            binding.tvPrice.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG // 设置中划线并加清晰

        }
    }

    fun setTextSizes(priceSize: Float = 20f, decimalSize: Float = 12f, symbolSize: Float = 12f) {
        binding.tvPrice.textSize = priceSize
        binding.tvDecimal.textSize = decimalSize
        binding.tvPriceSymbol2.textSize = symbolSize
        binding.tvPriceSymbol1.textSize = symbolSize
    }

    fun preMeasurePriceWidth(price: Any, currency: String?, currencySymbol: String?): Int {
        show(price, currency, currencySymbol)
        return (binding.tvPrice.paint.measureText(binding.tvPrice.text.toString())
                + binding.tvDecimal.paint.measureText(binding.tvDecimal.text.toString())
                + binding.tvPriceSymbol1.paint.measureText(binding.tvPriceSymbol1.text.toString())
                + binding.tvPriceSymbol2.paint.measureText(binding.tvPriceSymbol2.text.toString())).toInt()
    }


    fun showStyleHasOff(price: Any, currency: String?, currencySymbol: String?) {
        binding.tvPrice.setTextColor(color(com.hzjh.base.style.R.color.coreBlack2))
        binding.tvDecimal.setTextColor(color(com.hzjh.base.style.R.color.coreRed))
        binding.tvPriceSymbol2.setTextColor(color(com.hzjh.base.style.R.color.coreRed))
        binding.tvPriceSymbol1.setTextColor(color(com.hzjh.base.style.R.color.coreRed))
        show(price, currency, currencySymbol)
    }

    fun showDefaultColor() {
        binding.tvPrice.setTextColor(color(com.hzjh.base.style.R.color.coreRed))
        binding.tvDecimal.setTextColor(color(com.hzjh.base.style.R.color.coreRed))
        binding.tvPriceSymbol2.setTextColor(color(com.hzjh.base.style.R.color.coreRed))
        binding.tvPriceSymbol1.setTextColor(color(com.hzjh.base.style.R.color.coreRed))
    }

//    fun showStyleHasStrikethrough(price: Any, currency: String?, currencySymbol: String? ) {
//        binding.tvPriceStrikethrough.visible()
//        binding.tvPrice.paint.flags=Paint.STRIKE_THRU_TEXT_FLAG
//        binding.tvDecimal.paint.flags=Paint.STRIKE_THRU_TEXT_FLAG
//        binding.tvPriceSymbol2.paint.flags=Paint.STRIKE_THRU_TEXT_FLAG
//        binding.tvPriceSymbol1.paint.flags=Paint.STRIKE_THRU_TEXT_FLAG
//        binding.tvPrice.setTextColor(color(com.starblink.basic.style.R.color.sk_gray700))
//        binding.tvDecimal.setTextColor(color(com.starblink.basic.style.R.color.sk_gray700))
//        binding.tvPriceSymbol2.setTextColor(color(com.starblink.basic.style.R.color.sk_gray700))
//        binding.tvPriceSymbol1.setTextColor(color(com.starblink.basic.style.R.color.sk_gray700))
//        show(price,currency,currencySymbol)
//    }


    private fun getPriceStrList(isKrSymbol: Boolean): ArrayList<String> {
        var result = if (price is Double) {
            String.format("%.${2}f", price)
        } else {
            formatNum(price.toString(), 2)
        }

        var spans = arrayListOf<String>()
        if (isKrSymbol) {
            var p: String = addThousandSymbol(result, " ")
            result = p.replaceFirst(".", ",")
        } else if (currency == "GBP") {///英镑千位数逗号分隔
            result = addThousandSymbol(result, ",")
        }

        var size2 = result.indexOf(if (isKrSymbol) "," else ".")
        if (size2 > 0) {
            spans.add(result.substring(0, size2))
            spans.add(result.substring(size2))
        } else {
            spans.add(result)
        }
        return spans
    }

    private fun addThousandSymbol(result: String, char: String): String {
        var size = result.indexOf(".")
        var count = 0
        var p = ""
        for (index in size - 1 downTo 0) {
            p = result[index] + p
            count++
            if (count % 3 == 0 && index != 0) {
                p = char + p
            }
        }
        if (result.length > size && size > 0) {
            p += result.substring(size)
        }
        return p
    }

    private fun getCurrencySymbol(currency: String?): String {

        return when (currency) {
            "USD" -> "\$"

            "DKK"
            -> "kr."

            "SEK"
            -> "kr"

            "NOK"
            -> "kr"

            "EUR"
            -> "€"

            "GBP"
            -> "£"

            "CNY"
            -> "¥"

            "CAD"
            -> "C\$"

            "ISK"
            -> "Íkr"

            "CZK"
            -> "Kč"

            "PLN"
            -> "zł"

            "MXN"
            -> "Mex\$"

            else -> ""
        }
    }

    private fun formatNum(num: String, postion: Int): String {
        var plusStr = ""
        for (i in 0 until postion) {
            plusStr = plusStr.plus("0")
        }
        return if (num.contains(".")) {
            if (postion == 0) {
                return num.substring(0, num.indexOf('.'))
            }
            if (num.length - num.indexOf(".") - 1 >= postion) {
                num.substring(0, num.indexOf('.') + postion + 1)
            } else {
                (num.plus(plusStr))
                    .substring(0, num.indexOf('.') + postion + 1)
            }
        } else {
            num.plus(".").plus(plusStr)
        }
    }

    fun setPriceColor(color: Int) {
        binding.tvPrice.setTextColor(color)
        binding.tvPriceSymbol1.setTextColor(color)
        binding.tvDecimal.setTextColor(color)
        binding.tvPriceSymbol2.setTextColor(color)
    }
}